package com.scsoft.dataacceptor.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scsoft.dataacceptor.entity.VocSummaCanUser;
import com.scsoft.dataacceptor.task.VocSummaCanTask;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class VocLoginClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	private static Logger log = LoggerFactory.getLogger("suma");
	private VocSummaCanTask vocSummaCanTask;
	
	public VocLoginClientHandler(VocSummaCanTask vocSummaCanTask) {
		this.vocSummaCanTask = vocSummaCanTask;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf response) throws Exception {
		if (log.isInfoEnabled()) {	
			log.info("client receive response data length:" + response.readableBytes());
		}
		byte[] rep = new byte[response.readableBytes()];
		response.readBytes(rep);
		String res = new String(rep, "UTF-8");
		if (log.isInfoEnabled()) {
			log.info(res);
		}
		if (null != res && res.indexOf("user_load") > 0) {
			VocSummaCanUser user = parseToUser(res);
			log.info(user.toString());
			if (null != user && "ok".equals(user.getStatus())) {
				vocSummaCanTask.setDbpass(user.getDbpass());
				
			}
		}
	}

	private VocSummaCanUser parseToUser(String result) {
		try {
			String[] array = result.split("\\|");
			VocSummaCanUser user = new VocSummaCanUser();
			user.setOper(array[1]);
			user.setAccount(array[2]);
			user.setStatus(array[3]);
			if ("ok".equals(array[3])) {
				user.setDbpass(array[4]);
				String dbHostPort = array[5];
				String dbHost = dbHostPort.substring(0, dbHostPort.indexOf(":"));
				String dbPort = dbHostPort.substring(dbHostPort.indexOf(":") + 1);
				user.setDbhost(dbHost);
				user.setDbport(Integer.parseInt(dbPort));
			}
			return user;
		} catch (Exception e) {
			log.warn("parse to user exception!", e);
			return null;
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
}